<?php
/**
 * 个人中心，红包
 * Class MeRed
 */
namespace App;
defined('IN_IA') or exit('Access Denied');
use Model\MediaVideoMod;
use Model\OrderMod;
use Model\RedMod;
use Model\RedRecordMod;
use Model\RefundMod;
use Pub\tool\Tool;
use Pub\wx\WxPay;

class MeRed extends Action
{
    private $Red = null;
    private $RedRecord = null;  //红包记录
    private $Order = null; //支付订单
    private $Refund = null; //退款订单
    private $MediaVideo = null;

    public function __construct()
    {
        parent::__construct();
        $this->Red = new RedMod();
        $this->getUid();
    }

    /**
     * 获取指定用户的红包列表
     * @param Number uid 用户id
     */
    public function getList()
    {
        $_list = $this->Red->findAll(
            array(
                'uniacid'=>$this->_uniacid,
                'uid'=>$this->_uid,
                'status >'=>1,
                'status <'=>9
            ),
            array(
                'limit'=>$this->_gpc['limit'],
                'order'=>array('id','desc','status','asc')
            ),
            array('id','type','red_type','title','media','number','already_number','money','time','status')
        );
        if(count($_list) > 0){
            foreach($_list as $_k=>$_v){
                if($_v["red_type"] == "pic"){
                    $_list[$_k]["media"] = tomedia($_v["media"]);
                }else if($_v["red_type"] == "video"){
                    $_list[$_k]["media"] = $this->mediaToVideoThumb($_v["media"]);
                }
                $_list[$_k]['status'] = $this->getRedStatus($_v);
                $_list[$_k]['time'] = date('Y-m-d H:i',$_v['time']);
            }
            $this->_result = array('status'=>'success','data'=>$_list);
        }
        $this->result($this->_result);
    }

    /**
     * 获取红包状态
     * @param array $_detail 一个红包的详细内容
     * @return string 红包的状态
     */
    private function getRedStatus($_detail)
    {
        $_status = $_detail['status'];
        if(($_detail['already_number'] >= $_detail['number']) && $_detail['status'] == 2){
            $this->Red->update(array('status'=>3),array('id'=>$_detail['id']));
            $_status = 3;
        }
        return $_status;
    }

    /**
     * 通过红包的media获取视频红包的封面
     * @param string $_media 素材的地址source
     * @return string 封面地址
     */
    private function mediaToVideoThumb($_media)
    {
        if(!$this->MediaVideo instanceof MediaVideoMod) $this->MediaVideo = new MediaVideoMod();
        $_media_video = $this->MediaVideo->findOne(array("source"=>$_media),array("thumb"));
        return tomedia($_media_video["thumb"]);
    }

    /**
     * 修改红包状态
     * @param string red_id 红包id
     * @param string status 要更改的目标状态
     */
    public function changeStatus()
    {
        $_status = $this->_gpc['status'];
        $_red_id = $this->_gpc['red_id'];
        $_red = $this->Red->findOne(array('id'=>$_red_id),array('status'));
        if($_red['status'] == $_status){
            $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'修改失败');
            $this->result($this->_result);
        }
        if($_red['status'] == 4 && $_status == 9){
            if(!$this->refund($_red_id)){
                $this->_result = array('status'=>2,'err_status'=>2,'err_msg'=>'红包余额退款失败');
                $this->result($this->_result);
            }
        }
        if($this->Red->update(array('status'=>$_status),array('id'=>$_red_id))){
            $this->_result = array('status'=>'success');
        }
        $this->result($this->_result);
    }

    /**
     * 删除红包并且退款
     * @param string $_red_id 红包id
     * @return boolean 退款是否成功
     */
    private function refund($_red_id)
    {
        $_red = $this->Red->findOne(array('id'=>$_red_id),array('type','already_number','number','money','uid'));
        if($_red['already_number'] >= $_red['number']) return true;
        //退款金额
        $_refund_money = 0;
        if($_red['type'] == 2){
            $_refund_money = ($_red['number'] - $_red['already_number']) * $_red['money'];
        }else{
            $this->RedRecord = new RedRecordMod();
            $_already_money = $this->RedRecord->sum(array("uid !="=>0,"red_id"=>$_red_id),"money");
            $_refund_money = $_red["money"] - $_already_money;
        }
        //支付订单
        $this->Order = new OrderMod();
        $_order = $this->Order->findOne(array('source'=>'red','source_id'=>$_red_id),array('money','order_id'));
        //创建退款订单
        if(!$_refund_order_id = $this->createRefundOrder($_red['uid'],$_refund_money,$_order['order_id'])){
            $this->_result = array('status'=>'error','err_status'=>3,'err_msg'=>'创建退款订单失败');
            $this->result($this->_result);
        }
        //微信退款
        $WxPay = new WxPay($_order['order_id']);
        $_result = $WxPay->refund($_refund_order_id,$_order['money'],$_refund_money,\Pub\tool\Setting::get(\Pub\tool\Setting::WEB_NAME).'余额退款');
        if($_result['status'] == 'success' || $_result['err_msg'] == '订单已全额退款'){
            return true;
        }else{
            $this->Refund->update(array('status'=>2),array('order_id'=>$_refund_order_id));
            $this->_result = array('status'=>'error','err_status'=>4,'err_msg'=>$_result['err_msg']);
            $this->result($this->_result);
        }
    }

    /**
     * 创建退款订单
     * @param string $_uid 用户id
     * @param string $_money  退款金额
     * @param string $_pay_order_id 支付订单
     * @return bool|string 成功返回退款订单号 失败返回false
     */
    private function createRefundOrder($_uid,$_money,$_pay_order_id)
    {
        $_order_id = Tool::createOrder();
        $_data = array(
            'uniacid'=>$this->_uniacid,
            'uid'=>$_uid,
            'order_id'=>$_order_id,
            'pay_order_id'=>$_pay_order_id,
            'money'=>$_money,
            'time'=>TIMESTAMP
        );
        $this->Refund = new RefundMod();
        if($this->Refund->insert($_data)){
            return $_order_id;
        }else{
            return false;
        }
    }
}
